package com.gt.web.controller.app.login;

import cn.hutool.json.JSONObject;
import com.gt.app.domain.WXRequestParam;
import com.gt.common.core.domain.entity.SysUser;
import com.gt.common.utils.SecurityUtils;
import com.gt.system.service.ISysUserService;
import com.gt.common.app.WXUser;
import com.gt.common.core.domain.AjaxResult;
import com.gt.common.core.domain.model.LoginUser;
import com.gt.framework.web.service.SysLoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;

/**
 * <p>
 * 登录接口 前端控制器
 * </p>
 *
 * @author caidesheng
 */
@Slf4j
@RestController
@RequestMapping("login")
@Api(tags = "登录接口")
public class LoginController {

    // 微信登录接口URL
    @Value("${wx.wxLoginURL}")
    private String WX_LOGIN_URL;
    // 微信小程序AppID
    @Value("${wx.appId}")
    private String APP_ID;
    // 微信小程序AppSecret
    @Value("${wx.appSecret}")
    private String APP_SECRET;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private ISysUserService userService;

    @ApiOperation(value = "微信登录接口")
    @PostMapping(value = "wxLogin")
    public AjaxResult wxLogin(@RequestBody WXRequestParam wxRequestParam) {

        String url = WX_LOGIN_URL + "?appid=" + APP_ID + "&secret=" + APP_SECRET + "&js_code=" + wxRequestParam.getCode() + "&grant_type=authorization_code";

        // 发送POST请求，获取微信登录凭证
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            // 创建HttpPost请求
            HttpPost httpPost = new HttpPost(url);
            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            // 设置请求参数
            StringEntity requestEntity = new StringEntity("", StandardCharsets.UTF_8);
            httpPost.setEntity(requestEntity);
            // 发送请求，获取响应
            HttpResponse response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String responseBody = EntityUtils.toString(entity);
            JSONObject jsonObject = new JSONObject(responseBody);

            if (jsonObject.get("openid") == null) {
                String errcode = jsonObject.get("errcode").toString();
                return AjaxResult.error(errcode);
            }
            String openid = jsonObject.get("openid").toString();
            LoginUser loginUser = sysLoginService.openIdLogin(openid);
            AjaxResult success = AjaxResult.success(loginUser.getUser());
            success.put("token", loginUser.getToken());
            success.put("isNew",loginUser.getIsNew());
            return success;
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

}
